/**
 * @description admin controller
 */

const { ErrorRes, SuccessRes } = require('../res-model/index')
const { loginFailInfo } = require('../res-model/failInfo')
const doCrypto = require('../utils/crypto')
const { jwtSign } = require('../utils/jwt')
const { findOneAdmin, createAdmin, updateAdmin } = require('../service/admin')

/**
 * 登录
 * @param {string} username username
 * @param {string} password password
 */
async function login(username, password = '') {
  const info = await findOneAdmin(
    username,
    doCrypto(password) // 密码要加密
  )
  if (!info) {
    // 登录未成功
    return new ErrorRes(loginFailInfo)
  }

  // 更新最后登录时间
  try {
    await updateAdmin(info.username, { latestLoginAt: new Date() })
  } catch (error) {
    console.error('更新最后登录时间错误', error) // 只记录错误，不是主要错误，不影响登录逻辑
  }
  // 登录成功
  return new SuccessRes({
    token: jwtSign({ username: info.username, _id: info._id, nickName: info.nickName })
  })
}

/**
 * 注册用户
 * @param {string} username username
 * @param {string} password password
 * @param {string} nickName nickName
 */
async function register(username, password, nickName = '') {
  const adminInfo = await findOneAdmin(username, doCrypto(password))
  if (adminInfo) return adminInfo

  const adminData = {
    username,
    password: doCrypto(password),
    nickName
  }

  const newAdmin = await createAdmin(adminData)
  return newAdmin
}

module.exports = {
  login,
  register
}
